package com.smedi.ismedi.file.core.infrastructure;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
public class FileUtil {
    public static MultipartFile fileToMultipartFile(File inputFile) {
        String probeContentType = null;
        try {
            probeContentType = Files.probeContentType(inputFile.toPath());
        } catch (Exception exception) {
            log.error("获取文件内容类型");
        }
        FileItem fileItem = new DiskFileItem("file", probeContentType, false, inputFile.getName(), (int) inputFile.length(), inputFile.getParentFile());
        try (OutputStream outputStream = fileItem.getOutputStream()) {
            outputStream.write(Files.readAllBytes(Paths.get(inputFile.getAbsolutePath())));
        } catch (Exception exception) {
            log.error("file转换MultipartFile失败");
        }
        return new CommonsMultipartFile(fileItem);
    }

    public static File multipartFileToFile(MultipartFile inputFile) {
        File tempFile = null;
        String tempFileName = UUID.randomUUID().toString();
        String extension = FilenameUtils.getExtension(inputFile.getOriginalFilename());

        if (inputFile.getSize() <= 0) {
            return null;
        }

        try {
            tempFile = File.createTempFile(tempFileName, "." + extension);
        } catch (Exception exception) {
            log.info("临时文件创建失败{}", exception.getMessage());
        }

        try {
            assert tempFile != null;
            inputFile.transferTo(tempFile);
        } catch (Exception exception) {
            log.info("文件转换失败{}", exception.getMessage());
        }

        return tempFile;
    }
}
